const {getAccessToken, sign, encText} = require('../../utils/util');
const request = require('request');
let config = require('../../config/config');
/**
 * 脏腑健康api-问诊回答
 * @param req
 * @param resq
 * @param next
 * @returns {Promise<void>}
 */
module.exports = async (req, resq, next) => {
    // 1.获取accesstoken
    let accessToken = await getAccessToken();

    // 2.准备问诊回答数据：第三方单据id和问诊回答数据
    // 务必保证每个问题都有答案，如果用户没有回答则使用默认答案（defaultOption）
    let outId = 1;
    let inquiryAnswerList = [
        {questionIndex: 1, answerCode: '经常'},
        {questionIndex: 2, answerCode: '没有'},
        {questionIndex: 3, answerCode: '没有'},
        {questionIndex: 4, answerCode: '没有'}
    ]

    // 3.加密和签名数据
    let signature = sign(outId);
    let sourceData = {
        outId: outId,
        inquiryAnswers: inquiryAnswerList
    }
    let encryptData = encText(JSON.stringify(sourceData));

    // 4.上传问诊答案
    request.post({
        url: config.tongueInquiryTaskUrl,
        encoding: null,
        formData: {
            outId: outId,
            signature: signature,
            encryptData: encryptData
        },
        headers: {"Authorization": "Bearer " + accessToken},
        json: true
    }, (err, response, body) => {
        if (!err) {
            // body.code=0表示上传成功：
            // （1）body.data表示预计等待检测时间，
            // （2）检测的结果会回传到您设置的returnUrl上
            console.log(body);
            resq.json(body)
        } else {
            resq.json(err)
        }
    })
}
